package com.jcf.springboot.controller.business;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jcf.springboot.common.R;
import com.jcf.springboot.entity.business.Member;
import com.jcf.springboot.entity.vo.LoginVo;
import com.jcf.springboot.security.util.JwtUtil;
import com.jcf.springboot.service.MemberService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jjj
 * @since 2021-03-15
 */

@CrossOrigin
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JwtUtil jwtUtil;
    @Resource
    private MemberService memberService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping("login")
    public R login(@RequestBody LoginVo loginVo) {
        QueryWrapper queryWrapper = new QueryWrapper<Member>();
        queryWrapper.eq("member_name", loginVo.getMemberName());
        queryWrapper.eq("member_password", loginVo.getMemberPassword());
        Member one = memberService.getOne(queryWrapper);
        if (one != null && loginVo.getMemberPassword().equals(one.getMemberPassword())) {
            Map map = memberService.sealData(one);
            return R.ok().data(map).message("登录成功");
        }
        else {
            return R.error().message("用户名或密码输入错误");
        }

    }
    @GetMapping("getList")
//    @PreAuthorize("hasRole('ROLE_admin')")
    public R getList(String query,Integer pagenum,Integer pagesize) {
        System.out.println("methodA running in thread: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());

        Page<Member> page = new Page<>(pagenum, pagesize);
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("member_id","member_name", "member_password", "member_phone", "member_email", "member_birthday");
        if(!StringUtils.isEmpty(query)){
            queryWrapper.like("member_name", query);
        }
        memberService.page(page, queryWrapper);
        List<Member> list = page.getRecords();
        long total = page.getTotal();
        Map<Object, Object> map = new HashMap<>();
        map.put("value",list);
        map.put("total", total);
        if (!StringUtils.isEmpty(list)) {
            return R.ok().message("获取会员列表成功").data(map);
        } else {
            return R.error().message("获取会员列表失败");
        }
    }

    @PostMapping("addMember")
    public R addMember(@RequestBody Member member) {
        boolean b = memberService.save(member);
        if (b) {
            rabbitTemplate.convertAndSend("mail.welcome",member);
            return R.ok().message("添加会员成功");
        } else {
            return R.error().message("添加会员失败");
        }
    }

    @GetMapping("getMemberById")
    public R getMemberById(String id) {
        Member member = memberService.getById(id);
        if (!StringUtils.isEmpty(member)) {
            return R.ok().message("获取会员信息成功").data(member);
        } else {
            return R.error().message("获取会员信息失败");
        }
    }

    @PostMapping("editMember")
    public R editMember(@RequestBody Member member){
        Boolean flag =  memberService.updateMember(member);
        if(flag){
            return R.ok().message("编辑成功");
        } else {
            return R.error().message("编辑失败");
        }

    }

    @DeleteMapping("deleteMember/{id}")
    public R deleteMember(@PathVariable String id){
        boolean b = memberService.removeById(id);
        if(b){
            return R.ok().message("删除成功");
        } else {
            return R.error().message("删除失败");
        }
    }

    @DeleteMapping("batchDelete")
    public R batchDelete(@RequestParam("idList") List<String> idList){
        boolean b = memberService.removeByIds(idList);
        if(b){
            return R.ok().message("删除成功");
        } else {
            return R.error().message("删除失败");
        }
    }

    @GetMapping(value="/export",produces = "application/octet-stream")
    public void exportMember(HttpServletResponse response){
        List<Member> list = memberService.list(new QueryWrapper<>());
        ExportParams params = new ExportParams("客户表", "客户表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, Member.class, list);
        ServletOutputStream out = null;
        try{
            response.setHeader("content-type","application/octet-stream");
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode("员工表.xls", "UTF-8"));
            out = response.getOutputStream();
            workbook.write(out);
        }catch (IOException e){
            e.printStackTrace();
        }finally{
            if(null != out){
                try{
                    out.close();

                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

    @PostMapping("/import")
    public R importData(MultipartFile file) throws IOException {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        try
        {
            List<Member> list = ExcelImportUtil.importExcel(file.getInputStream(), Member.class, params);
            if(memberService.saveBatch(list)){
                return R.ok().message("导入成功");
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return R.error().message("导入失败");

    }


}

